package com.north.light.libltobserver.impl;

import com.north.light.libltobserver.pool.LTObserverPool;
import com.north.light.libltobserver.thread.LTThread;
import com.north.light.libltobserver.thread.LTThreadUtils;

import java.io.Serializable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * FileName: LTObserverSender
 * Author: lzt
 * Date: 2022/11/17 10:39
 * 发送者
 */
public class LTObserverSender implements Serializable {

    //默认线程
    private LTThread mCurrentThread = LTThread.MAIN;

    public LTObserverSender() {

    }

    public LTObserverSender thread(LTThread thread) {
        this.mCurrentThread = thread;
        return this;
    }


    //事件发送
    public <T> void send(String tag, T t) {
        if (!LTObserverPool.getInstance().checkExist(tag)) {
            return;
        }
        LTObserverReceiver builder = LTObserverPool.getInstance().getBuilder(tag);
        if (builder != null) {
            if (mCurrentThread.getType() == LTThread.MAIN.getType()) {
                //MAIN
                LTThreadUtils.getInstance().runOnUIThread(new Runnable() {
                    @Override
                    public void run() {
                        builder.send(t);
                    }
                });
            }
        }
    }

    public <T> void send(T t) {
        ConcurrentHashMap<String, LTObserverReceiver> builderConcurrentHashMap = LTObserverPool.getInstance().getObserverBuilderMap();
        if (builderConcurrentHashMap == null || builderConcurrentHashMap.size() == 0) {
            return;
        }
        for (Map.Entry<String, LTObserverReceiver> keyEntry : builderConcurrentHashMap.entrySet()) {
            send(keyEntry.getKey(), t);
        }
    }

}
